program main

    use iso_c_binding
    use readfile_module, only: readfile, read_lines, string_t, readfile_c, readfile_b
    use timer_module, only: timer
    implicit none
    type(string_t), allocatable :: lines(:)
    character(c_char), allocatable :: content(:)
    type(timer) :: tmr
    integer :: i, length, N = 1000

100 format(a, t40, g0.4, 1x, 's')
101 format("Check:", 1x, a, ", size:", 1x, i0, 1x, i0)

    print "(a)", "# Benchmarking readfile"
    open (1, file='app/readfile.f90', status='old', action='read')
    call tmr%tic()
    do i = 1, N
        rewind (1)
        lines = read_lines(1)
    end do
    print 100, 'Elapsed time (FPM):', tmr%toc()
    print 101, lines(size(lines))%s, size(lines), len(lines(size(lines))%s)

    call tmr%tic()
    do i = 1, N
        rewind (1)
        lines = readfile(1)
    end do
    print 100, 'Elapsed time (optimized Fortran):', tmr%toc()
    print 101, lines(size(lines))%s, size(lines), len(lines(size(lines))%s)

    call tmr%tic()
    do i = 1, N
        rewind (1)
        lines = readfile_c(1, 'app/readfile.f90')
    end do
    print 100, 'Elapsed time (C interface):', tmr%toc()
    print 101, lines(size(lines))%s(:len(lines(size(lines))%s) - 1), size(lines), len(lines(size(lines))%s)
    close (1)

    open (1, file='app/readfile.f90', access="stream", form="unformatted")
    call tmr%tic()
    do i = 1, N
        rewind (1)
        lines = readfile_b(1)
    end do
    print 100, 'Elapsed time (Fortran binary):', tmr%toc()
    print 101, lines(size(lines))%s(:len(lines(size(lines))%s)), size(lines), len(lines(size(lines))%s)
    close (1)
    print *, lines(1)%s(len(lines(1)%s)-1:len(lines(1)%s)) == achar(13)//c_new_line, &
        lines(1)%s(len(lines(1)%s)-1:len(lines(1)%s))

    ! check for another file
    print "(/a)", "# Check for another file"
    open (1, file='fpm.toml', status='old', action='read')
    rewind (1)
    lines = readfile(1)
    print 101, lines(size(lines))%s, size(lines), len(lines(size(lines))%s)

    rewind (1)
    lines = readfile_c(1, 'fpm.toml')
    print 101, lines(size(lines))%s(:len(lines(size(lines))%s) - 1), size(lines), len(lines(size(lines))%s)

    rewind (1)
    lines = read_lines(1)
    print 101, lines(size(lines))%s, size(lines), len(lines(size(lines))%s)
    close (1)

end program main
